package com.test.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.*;

/**
 * Created by yang on 17/3/6.
 */
public class Get {

    public static String sendGet(String url, Map<String, Object> params) throws Exception{

        // 先判断传入的map是否为空
        if (params != null && !params.isEmpty()){
            List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(params.size());
            for (String key : params.keySet()){
                pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
            }
            url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs), "utf-8");
//            System.out.println(url);
        }

        // 创建httpclient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httpget实例，传url
        org.apache.http.client.methods.HttpGet httpGet = new org.apache.http.client.methods.HttpGet(url);
        // 创建返回实例，执行httpget
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 判断是否返回200
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200){
            httpGet.abort();
            throw new RuntimeException("HttpClient error status code : " + statusCode);
        }
        // 创建httpentity消息实体
        HttpEntity entity = response.getEntity();
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            response.close();
            return result;
        }else {
            return null;
        }
    }
}
